package com.ruoyi.business.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.business.domain.TOrderInfo;
import com.ruoyi.business.domain.TOrderQrcodeInfo;
import com.ruoyi.business.domain.TRecipientInfo;
import com.ruoyi.business.param.MsgPayResult;
import com.ruoyi.business.response.ErrorResponseData;
import com.ruoyi.business.response.ResponseData;
import com.ruoyi.business.response.SuccessResponseData;
import com.ruoyi.business.service.BasePayment;
import com.ruoyi.business.service.ChargeService;
import com.ruoyi.business.service.ITOrderQrcodeInfoService;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.HttpResponse;
import com.ruoyi.common.utils.HttpUtils;
import com.ruoyi.common.utils.MoneyUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.payment.dongwopay.DongWoPayUtils;
import com.ruoyi.common.utils.payment.pbqzpay.PubuPayUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Service("zidiantongPayService")
public class ZdtPayServiceImpl extends BasePayment {


    @Resource
    private ChargeService chargeService;

    @Resource
    private ITOrderQrcodeInfoService itOrderQrcodeInfoService;

    @Override
    public JSONObject createPayOrder(TOrderInfo orderInfo) throws Exception {
        JSONObject jsonObject = new JSONObject();
        TRecipientInfo userRecipientInfo = userRecipientService.selectTRecipientInfoById(orderInfo.getRecipientId());
        HashMap<String, String> headerMap = new HashMap();
        HashMap<String, String> dataMap = new HashMap();
        headerMap.put("User-Agent","Mozilla/5.0 (iPhone; CPU iPhone OS 18_1_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 Html5Plus/1.0 (Immersed/47) uni-app");
        headerMap.put("Connection","keep-alive");
        headerMap.put("content-type","application/json");
        headerMap.put("Accept-Encoding","gzip,compress,br,deflate");
        String payInfo = "";

        JSONObject proxyObj = new JSONObject();
        proxyObj = commonService.getPoxyIp("");
        orderInfo.setProxyIp(proxyObj.getString("ip") + ":" + proxyObj.getString("prot"));
        String accountJson = userRecipientInfo.getAccountJson();
        JSONObject  accountObj = JSONObject.parseObject(accountJson);
        String ck = accountObj.getString("ck");
        headerMap.put("iToken",ck);
        String submitPayUrl = "https://mch.zdt.bytedt.cn/api/pay/zftPay";
        JSONObject reqOrderObj = new JSONObject();
        reqOrderObj.put("amount",MoneyUtil.fenToYuan(orderInfo.getMoney()+""));
        reqOrderObj.put("wayCode","ALI_ZFT_FACE");
        reqOrderObj.put("wayType","qrCode");
        reqOrderObj.put("payDataType","codeImgUrl");
        reqOrderObj.put("hbFqNum","");
        reqOrderObj.put("hbFqSellerPercent","");
        String payInfoStr = HttpUtils.sendJsonMessageByProxyIp(submitPayUrl,headerMap,reqOrderObj.toJSONString(),orderInfo.getProxyIp());
        logger.info("create请求参数：{}",submitPayUrl);
        JSONObject  payInfoObj = JSONObject.parseObject(payInfoStr);


        if(payInfoObj.getIntValue("code")!=0){
            jsonObject.put("code","200");
            jsonObject.put("msg","生成收款单失败:"+payInfoObj.getString("msg"));
            logger.info("========修改收款账号为不可用==============="+payInfoObj.getString("msg"));
            userRecipientInfo.setOnline(0);
            userRecipientInfo.setDisabledInfo("生成失败："+payInfoObj.getString("msg"));
            userRecipientService.updateTRecipientInfo(userRecipientInfo);
            return jsonObject;
        }

        logger.info("create返回：{}",payInfoObj.toJSONString());

        String payUrlImg = payInfoObj.getJSONObject("data").getString("payData");
        String payOrderId = payInfoObj.getJSONObject("data").getString("payOrderId");
        String filePath = RuoYiConfig.getUploadPath();
        logger.info("保存地址：{}", filePath + "/" +userRecipientInfo.getChannelAccount()+"_" + payOrderId + ".png");
        FileUtils.downloadByCommonIO(payUrlImg, filePath, userRecipientInfo.getChannelAccount()+"_" + payOrderId + ".png");
        String payUrl = decodeQR(filePath + "/" + userRecipientInfo.getChannelAccount()+"_" + payOrderId + ".png");

        jsonObject.put("payUrl",payUrl);
        jsonObject.put("orderNo",payOrderId);
        jsonObject.put("code","200");
        return jsonObject;
    }

    @Override
    public ResponseData smartReissueOrder(TOrderInfo orderInfo) throws Exception {
        if (StringUtils.isBlank(orderInfo.getPay3rdOrderNo())) {
            return new ErrorResponseData("未获取到三方订单号");
        }

        TRecipientInfo userRecipientInfo = userRecipientService.selectTRecipientInfoById(orderInfo.getRecipientId());
        String accountJson = userRecipientInfo.getAccountJson();
        JSONObject accountObj = JSONObject.parseObject(accountJson);
        String token = accountObj.getString("ck");
        HashMap<String, String> headerMap = new HashMap();
        headerMap.put("iToken",token);
        headerMap.put("User-Agent","Mozilla/5.0 (iPhone; CPU iPhone OS 18_1_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 Html5Plus/1.0 (Immersed/47) uni-app");

        String qryOrderUrl = "https://mch.zdt.bytedt.cn/api/payOrder/get?payOrderId="+orderInfo.getPay3rdOrderNo();
        logger.info("查单 请求地址:{}，请求参数：{}",qryOrderUrl,orderInfo.getPay3rdOrderNo());

        HttpResponse qryOrderRes = HttpUtils.httpFormGet(qryOrderUrl,headerMap,token,"");
        JSONObject  qryOrderResObj = JSONObject.parseObject(qryOrderRes.getBody());
        logger.info("qryOrderUrl 返回：{}",qryOrderResObj.toJSONString());
        if(qryOrderResObj.getIntValue("code")==0){
            if(qryOrderResObj.getJSONObject("data").getIntValue("state")==2 && qryOrderResObj.getJSONObject("data").getIntValue("notifyState")==1){
                MsgPayResult msgPayResult = new MsgPayResult();
                msgPayResult.setChannel(orderInfo.getChannel());
                msgPayResult.setTradeNo(orderInfo.getId().toString());
                msgPayResult.setChannelAccount(userRecipientInfo.getChannelAccount());
                msgPayResult.setOrderId(orderInfo.getPay3rdOrderNo());
                msgPayResult.setRealMoney(MoneyUtil.fenToYuan(orderInfo.getMoney() + ""));
                msgPayResult.setUid(userRecipientInfo.getUserId().toString());
                msgPayResult.setChannelPayMsgResult(qryOrderResObj.toJSONString());
                ResponseData responseData = chargeService.updateOrderPayResult(false, orderInfo.getId(), msgPayResult, false);
                chargeService.notifyUserPaySucc(orderInfo.getId());
                logger.info("ZDT订单回调..订单号：" + orderInfo.getId() + " 金额：" + orderInfo.getMoney() + " 处理结果：{}", responseData.getSuccess());
            }

        }
        return new SuccessResponseData();
    }


    public JSONObject createWxPayOrder(TOrderInfo orderInfo) throws ServiceException, UnsupportedEncodingException {
        return null;
    }



}
